/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.PasswordChangeRequest;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author wei
 */
@Stateless
public class PasswordChangeRequestFacade extends AbstractFacade<PasswordChangeRequest> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public PasswordChangeRequestFacade() {
        super(PasswordChangeRequest.class);
    }

    private PasswordChangeRequest getRequestByHashId(String hashId) {
        Query query = em.createQuery("Select s from PasswordChangeRequest s WHERE s.hashedId=:hash");
        query.setParameter("hash", hashId);

        return (PasswordChangeRequest) query.getSingleResult();
    }

    public boolean isRequestValid(String email, String hashId) {
        boolean valid = false;
        try {
            PasswordChangeRequest request = getRequestByHashId(hashId);
            if(!request.isUsed() && request.getEmail().equals(email))
                valid = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return valid;
    }
    
    public void markUsed(String hashId){
        try {
            PasswordChangeRequest request = getRequestByHashId(hashId);
            request.setUsed(true);
            edit(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
